<template>
  <div class="content">
    <div class="conBox">
      <div v-show="showFlag">
        <div class="chooseText">
          <span
            :class="idx === index ? 'curr' : ''"
            v-for="(item, index) in topData"
            :key="index"
            @click="topChooseClick(item, index)">
            {{ item }}
          </span>
          <p style="line-height: 30px; margin-left: 50px">自定义：</p>
          <DatePicker
            type="daterange"
            :clearable="false"
            :value="timeVal"
            @on-change="dataChoose"
            ref="oselect"
            :options="options"
            placeholder="请选择时间"
            style="width: 220px"></DatePicker>

          <div class="tan">
            取值条件：
            <em v-if="conditionsVal.create">创建</em>
            <em v-if="conditionsVal.visit">到访</em>
            <em v-if="conditionsVal.follow">跟进</em>
            <em v-if="!conditionsVal.create && !conditionsVal.visit && !conditionsVal.follow">暂无</em>
            <span @click="modifyClick">修改</span>
          </div>
        </div>
        <dt-search ref="search" :labelWidth="100" style="margin-top: 20px" @reset="onReset"></dt-search>
        <customTopListVue
          :fromType="'customerBig'"
          :topRocerdData="topRocerdData"
          @getClickData="getClickData"
          :showRight="false" />
        <div style="color: #f39216">
          共有{{ countVal.customerCount }}个客户，其中{{ countVal.customerUniqueCount }}个是唯一客户
        </div>
      </div>
    </div>
    <dynamic-header
      ref="dynamicHeader"
      @fieldCancel="fieldCancel"
      @headUpdate="headUpdate"
      :sourcedata="sourcedata"
      :targetdata="targetdata"></dynamic-header>
    <dt-grid
      ref="table"
      :columns="columns"
      :page="page"
      :onFetch="onFetch"
      :cell-height="80"
      @filter="filter"
      :row-style="rowStyle">
      <div class="flex btn-content" slot="btn">
        <div class="handles" style="margin-top: 5px">
          <Button type="primary" class="operation" @click="operationClick">查看导出记录</Button>
          <Button type="primary" @click="adjustHeader">调整表头排序</Button>
          <Button type="primary" v-if="unlocking('0216020100')" @click="exportData('0')">导出Excel</Button>
          <Button type="primary" v-if="unlocking('0216020200')" @click="exportData('1')">导出</Button>
          <Button type="default" @click="showSearchFun">{{ showFlag ? '收起筛选' : '展开筛选' }}</Button>
        </div>
      </div>
    </dt-grid>

    <Modal
      v-model="detailsFlag"
      title="客户详情"
      width="80%"
      :styles="{ top: '5%' }"
      :footer-hide="true"
      @on-cancel="markCancel">
      <detail-page v-if="detailsFlag" :detailsParams="detailsParams" @change="onDetailChange"></detail-page>
    </Modal>
    <preview-image :images="preViewImg" :showIndex="showIndex" ref="preViewImage"></preview-image>
    <Modal v-model="downModal" title="导出提示" @on-ok="downOk" ok-text="确认打包">
      <div>您当前导出的数据量较大，打包数据需要较长时间（稍后可以在下载中心进行下载数据）</div>
      <div>
        <img
          style="display: block; width: 90%; margin: 15px auto"
          class="login_header_img"
          src="@/assets/images/download.png" />
      </div>
    </Modal>

    <Modal
      v-model="conditionsFlag"
      title="设置取值条件"
      :footer-hide="true"
      :mask-closable="false"
      :closable="false">
      <div class="tips">
        <Icon type="ios-alert" size="24" color="#2d8cf0" />
        设置后，将在客户大表中，显示您所选日期范围内创建的客户、最近到访的客户或最近被跟进的客户
      </div>
      <div class="condit">
        <div class="conditCon">
          <p>
            <span>创建日期</span>
            <em>显示“创建日期”在所选日期范围内的客户</em>
          </p>
          <i-switch style="margin-top: 10px" v-model="conditionsVal.create"></i-switch>
        </div>
        <div class="conditCon">
          <p>
            <span>最近到访日期</span>
            <em>显示“最近到访日期”在所选日期范围内的客户</em>
          </p>
          <i-switch style="margin-top: 10px" v-model="conditionsVal.visit"></i-switch>
        </div>
        <div class="conditCon">
          <p>
            <span>最近跟进日期</span>
            <em>显示“最近跟进日期”在所选日期范围内的客户</em>
          </p>
          <i-switch style="margin-top: 10px" v-model="conditionsVal.follow"></i-switch>
        </div>
      </div>
      <div class="footer">
        <Button @click="conditionsOk" style="margin-left: 10px">确定</Button>
      </div>
    </Modal>
    <operation-record ref="operationRecord" :showBtn="false"></operation-record>
  </div>
</template>
<script>
  import detailPage from '../../casemanagement/allCustomersManagement/details.vue'
  import columnOpt from './opt/bigColumn'
  import clueCustomerMgr from '@/biz/customer/clueCustomer.js'
  import customerOptMgr from '@/biz/customer/customerOpt.js'
  import dynamicHeader from '@/components/dynamicHeader.vue'
  import receiverMgr from '@/biz/receiver/receiver'
  import userMgr from '@/biz/user'
  import searchBig from './opt/search'
  import homeMgr from '@/biz/buildingHome/home'
  import customTopListVue from '@/components/customTopList.vue'
  export default {
    components: {
      detailPage,
      dynamicHeader,
      customTopListVue
    },
    data() {
      return {
        exportType: 2,
        queryType: 0,
        levelValflag: true,
        conditionsVal: {
          create: true,
          visit: true,
          follow: true
        },
        conditionsFlag: false,
        topRocerdData: {},
        timeVal: [],
        options: {
          disabledDate(date) {
            return date && date.valueOf() < new Date().getTime() - 365 * 2 * 24 * 3600 * 1000
          }
        },
        topData: ['昨日', '今日', '本周', '本月', '本年'],
        idx: 3,
        startTime: '',
        endTime: '',
        downModal: false,
        showIndex: 0,
        preViewImg: [],
        sourcedata: [],
        targetdata: [],
        page: {
          total: 0,
          current: 1
        },
        columns: [],
        list: [],
        params: {},
        planListVal: [],
        userCustomerId: [],
        popLoading: true,
        popClass: '',
        followUpList: [],
        popLen: 0,
        detailsFlag: false,
        detailsParams: {},
        callPopLoading: true,
        callPopClass: '',
        callList: [],
        userMess: userMgr.info(),
        formValidate: {
          officeIds: [],
          buildingName: ''
        },
        countVal: {},
        mask: '',
        channelSource: [],
        showFlag: true
      }
    },
    async mounted() {
      clueCustomerMgr.getChannel(false)
      await this.getColumns()
      this.planList()
      this.chooseTime = homeMgr.resovleTime(3)
    },
    methods: {
      showSearchFun() {
        this.showFlag = !this.showFlag
        this.$refs.table.fixHeight()
      },
      operationClick() {
        this.$refs.operationRecord.show('export_customerBig', 'M_23', '')
      },
      modifyClick() {
        this.conditionsFlag = true
      },
      conditionsOk() {
        if (!this.conditionsVal.create && !this.conditionsVal.visit && !this.conditionsVal.follow) {
          this.$Message.warning('请至少开启一个取值条件')
        } else {
          this.conditionsFlag = false
          this.$refs.table.fetch()
        }
      },
      getClickData(val) {
        this.queryType = val.queryType
        this.$refs.table.fetch()
      },
      topChooseClick(item, index) {
        this.idx = index
        this.dataText = item
        this.$refs.oselect && this.$refs.oselect.handleClear()
        this.chooseTime = homeMgr.resovleTime(index)
        this.$refs.table.clearSort()
        this.$refs.table.fetch(true)
      },
      dataChoose(val) {
        if (val[0] != '' && val[1] != '') {
          this.idx = null
          this.chooseTime = {
            startTime: val[0],
            endTime: val[1]
          }
          this.$refs.table.fetch()
        }
      },
      filter(val) {
        if (val && !val.clueChannelIds) {
          this.channelSource = []
        }
      },
      channelChange(v) {
        this.channelSource = []
        v &&
          v.length &&
          v.forEach((item) => {
            this.channelSource.push(item.label)
          })
      },
      onReset() {
        this.checkParams = ''
        this.customerClueRecordIds = []
      },
      onFetch(data) {
        let arr = []
        if (data.planNameval && data.planNameval.length) {
          this.planListVal.forEach((item) => {
            if (data.planNameval.indexOf(item.id) != -1) {
              arr.push(item.planName)
            }
          })
          if (arr.length) {
            data.planNameList = arr
          }
        }
        if (data.authLocation && data.authLocation.length) {
          let arr2 = []
          this.$dt.dictInfo().authLocation.forEach((item) => {
            if (data.authLocation.indexOf(item.key) != -1) {
              arr2.push(item.value)
            }
          })
          if (arr2.length) {
            data.authLocations = arr2
          }
          delete data.authLocation
        }
        if (this.channelSource.length) {
          data.clueSourceChannelNames = this.channelSource
          delete data.clueChannelIds
        }
        data.startTime = this.chooseTime.startTime
        data.endTime = this.chooseTime.endTime
        data.openCreateTime = this.conditionsVal.create
        data.openVisitTime = this.conditionsVal.visit
        data.openFollowTime = this.conditionsVal.follow
        data.queryType = this.queryType
        this.params = data
        this.largeCustomerSummary()
        return customerOptMgr.largeCustomerList(this.params).then((res) => {
          res.list &&
            res.list.forEach((item) => {
              if (item.featurePhoto) {
                item.featurePhoto = item.featurePhoto && item.featurePhoto.split(',')
              } else {
                item.featurePhoto = []
              }
            })
          this.list = res.list
          this.page.total = res.total
          this.largeCustomerStatistics()
          return res.list
        })
      },
      rowStyle(e) {
        return {
          'background-color': Number(e.row.customerUnique) % 2 == 0 ? '#f8f8f8' : '#f1f1f1'
        }
      },
      downOk() {
        let params = {
          ...this.params
        }
        params.maskCustomerPhone = this.mask
        customerOptMgr.largeCustomerExport(params)
      },

      onDetailChange(val) {
        if (val && val.closeModal) {
          this.detailsFlag = false
        }
        this.$refs.table.fetch()
      },
      lookImg(val) {
        this.preViewImg = val
        this.$refs.preViewImage.show()
      },
      initData() {
        this.$refs.table.fetch()
      },
      fieldCancel() {
        this.$refs.dynamicHeader.hide()
      },
      adjustHeader() {
        this.$refs.dynamicHeader.show()
      },
      exportData(mask) {
        this.params.exportType = this.exportType
        if (this.params.orgIds && this.params.orgIds.length > 0) {
          if (!this.levelValflag) {
            this.$Modal.info({
              title: '提示',
              content: '只能导出单一子公司的客户，请重新选择组织'
            })
          } else {
            this.mask = mask
            if (this.page.total > 50000) {
              this.downModal = true
            } else {
              let params = { ...this.params }
              params.maskCustomerPhone = this.mask
              customerOptMgr.largeCustomerExport(params)
            }
          }
        } else {
          this.$Message.warning('请选择一个分公司')
        }
      },
      //打法
      planList() {
        customerOptMgr.planList().then((res) => {
          this.planListVal = res
        })
      },
      //获取统计
      largeCustomerStatistics() {
        customerOptMgr.largeCustomerStatistics(this.params).then((res) => {
          this.countVal = res
        })
      },
      //获取统计
      largeCustomerSummary() {
        let params = this.$tool.deepClone(this.params)
        delete params.queryType
        customerOptMgr.largeCustomerSummary(params).then((res) => {
          this.topRocerdData = res
        })
      },
      //获取表头
      getColumns() {
        customerOptMgr
          .customerBigHead({
            headType: 10012
          })
          .then((res) => {
            this.sourcedata = res.hideHead
            this.targetdata = res.showHead
            this.targetdata.forEach((item, index) => {
              item.disabled = item.fixed
            })
            this.columns = []
            let baseColumns = columnOpt.options(this)
            this.targetdata.forEach((item) => {
              let column = baseColumns.filter(
                (baseItem) => item.fieldKey == baseItem.field.split('_')[baseItem.field.split('_').length - 1]
              )
              if (column.length) {
                column[0].field = item.fieldKey
                this.columns.push(column[0])
              }
            })
            this.columns.push(baseColumns[baseColumns.length - 1])

            this.$refs.search.init(this.$refs.table, new searchBig(this).options(), this.formValidate)
            this.$refs.table.init(this)
            this.$refs.table.fetch()
          })
      },

      headUpdate(params) {
        params.updateHead = params.updateInfo
        delete params.buildingId
        params.headType = 10012
        customerOptMgr.customerBigHeadUpdate(params).then((res) => {
          this.getColumns()
          this.$nextTick(function () {
            this.$refs.dynamicHeader.hide()
          })
        })
      },
      viewClick(row) {
        if (row.dataType == 1) {
          this.detailsFlag = true
          this.detailsParams = {
            big: true,
            flag: 'clue',
            customerId: row.customerId,
            userCustomerId: row.userCustomerId,
            userId: row.userId,
            buildingId: row.buildingId
          }
        } else {
          this.detailsFlag = true
          this.detailsParams = {
            big: true,
            customerId: row.customerId,
            userCustomerId: row.userCustomerId,
            buildingId: row.buildingId,
            userId: row.userId
          }
        }
      },
      markCancel() {
        this.detailsFlag = false
      },
      getCallList(val) {
        this.callPopLoading = true
        this.callPopClass = ''
        this.callList = []
        receiverMgr.callRecordList({ userCustomerId: val.userCustomerId }).then((res) => {
          this.callPopLoading = false
          this.callList = res.records
        })
      },
      getFollowUp(val) {
        this.popLoading = true
        this.popClass = ''
        this.followUpList = []
        this.popLen = 0
        clueCustomerMgr
          .follow({
            page: 1,
            rows: 10,
            userCustomerId: val.userCustomerId,
            category: '4,12',
            customerId: val.customerId,
            buildingId: val.buildingId
          })
          .then((res) => {
            this.followUpList = res.records
            this.popLen = res.total
            this.updateFollow(val)
            this.popLoading = false
          })
      },
      updateFollow(val) {
        clueCustomerMgr
          .updateFollow({
            userCustomerId: val.userCustomerId,
            customerId: val.customerId,
            buildingId: val.buildingId,
            category: '4'
          })
          .then((res) => {
            if (String(res) == 'true') {
              val.newNews = 2
            }
          })
      }
    }
  }
</script>
<style lang="scss" scoped>
  .content {
    padding: 0 10px 10px;
    .topRecord {
      display: flex;
      flex-direction: row;
      .record1 {
        display: flex;
        flex-direction: row;
        cursor: pointer;
        p {
          text-align: center;
          padding: 0 20px;
          span {
            display: block;
            font-size: 20px;
            font-weight: bold;
            color: #000;
          }
          em {
            display: block;
            font-style: normal;
          }
        }
        p.curr2 {
          span {
            color: red;
            font-weight: bold;
          }
        }
        p.curr {
          span {
            color: #2d8cf0;
            font-weight: bold;
          }
        }
      }
      .recordBtn {
        padding: 0 20px;
        border-left: 1px #ccc solid;
        p {
          span {
            color: #2db7f5;
          }
        }
      }
    }
    .retainClass {
      margin-top: 20px;
    }
  }

  .handles {
    display: flex;
    align-items: center;
    flex-direction: row-reverse;
    > * {
      margin-left: 10px;
    }
  }

  .footer {
    text-align: center;
    margin-top: 20px;
    border-top: 1px #eee solid;
    padding-top: 20px;
    button {
      width: 80px;
      margin: 0 10px;
    }
  }
  .chooseText {
    margin: 10px 0;
    height: 40px;
    border-radius: 2px;
    padding: 5px;
    box-sizing: border-box;
    display: flex;
    flex-direction: row;

    span {
      height: 30px;
      border: #dcdee2 1px solid;
      width: 90px;
      text-align: center;
      line-height: 30px;
      font-size: 14px;
      color: #666;
      cursor: pointer;
      margin-right: 5px;
    }
    span.curr {
      border: #2d8cf0 1px solid;
      color: #2d8cf0;
    }
  }
  .tan {
    height: 32px;
    line-height: 32px;
    text-align: center;
    margin-left: 20px;
    background: #ffefc4;
    width: 280px;
    em {
      font-style: normal;
      margin-right: 10px;
    }
    span {
      color: #2d8cf0;
      border: none;
      margin-left: 10px;
      cursor: pointer;
    }
  }
  .tips {
    background: rgba(254, 252, 236, 1);
    display: inline-block;
    padding: 5px;
    margin-bottom: 10px;
    span {
      color: #2d8cf0;
      margin-right: 20px;
    }
  }
  .conditCon {
    margin-top: 15px;
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    p {
      span {
        font-size: 14px;
      }
      em {
        font-style: normal;
        display: block;
        color: #999;
      }
    }
  }
  .footer {
    display: flex;
    justify-content: flex-end;
    margin-top: 10px;
  }
  .conBox {
    position: relative;
  }
</style>
